package com.example.springbootmybatisplus.annotation;

import com.example.springbootmybatisplus.utils.MaskUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * &#064;ClassName  LogAspect
 * &#064;Description:  TODO
 * &#064;Author:  Sunny
 * &#064;Create:  2023-12-25 18:05
 * &#064;Version  1.0
 **/

@Component
@Aspect //切面 定义了通知和切点的关系
@Slf4j
public class SensitiveAspectTest {

    @Pointcut("@annotation(com.example.springbootmybatisplus.annotation.SensitiveAnnotation)")
    public void pt() {
    }


    //环绕通知
    @Around("pt()")
    public Object log(ProceedingJoinPoint point) throws Throwable {
        //保存日志
        return recordLog(point);

    }

    private Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object obj = joinPoint.proceed();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SensitiveAnnotation SensitiveAnnotation = method.getAnnotation(SensitiveAnnotation.class);
        String[] fieldNames = SensitiveAnnotation.field();
        if (Objects.nonNull(fieldNames) && fieldNames.length > 0) {
            for (Field field : obj.getClass().getDeclaredFields()) {
                ReflectionUtils.makeAccessible(field);
                Object value = field.get(obj);
                for (String fieldName : fieldNames) {
                    String aa = value == null ? "" : value.toString();
                    if(StringUtils.isNoneBlank(aa)&&Objects.equals(fieldName,(field.getName()))) {
                        switch (field.getName()) {
                            case "name":
                                String name = MaskUtil.chineseName((String) value);
                                ReflectionUtils.setField(field, obj, name);
                                break;
                            case "phone":
                                String phone = MaskUtil.maskPhone((String) value);
                                ReflectionUtils.setField(field, obj, phone);
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        }
        return obj;
    }


}